package com.travelgroup.exception;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.SaTokenException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e) {
        if (e instanceof BusinessException) {
            return R.error(e.getMessage());
        }
        if (e instanceof NoResourceFoundException) {
            return R.error("请求资源不存在");
        }
        if (e instanceof NotLoginException) {
            return R.error("未登录");
        }
        if (e instanceof NotPermissionException) {
            return R.error("没有权限");
        }
        if (e instanceof SaTokenException) {
            return R.error("其他权限异常，错误码：" + ((SaTokenException) e).getCode() + ",请联系管理员");
        }
        if (e instanceof MethodArgumentNotValidException) {
            return R.error(((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
        }
        log.error(e.getMessage(), e);
        return R.error("出现未知异常" + e.getClass().getSimpleName() + "，请联系管理员");
    }
}
